package com.example.recruit.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.recruit.common.R;
import com.example.recruit.entity.User;
import com.example.recruit.mapper.EmployerMapper;
import com.example.recruit.mapper.UserMapper;
import com.example.recruit.service.UserService;
import com.example.recruit.util.RegxPhoneNumber;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 用户管理类
 * loginUser
 * getCode
 * registerUser
 */
@RestController
@RequestMapping("/user")
@Slf4j
@CrossOrigin(origins = "*")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    EmployerMapper employerMapper;

    /**
     * 登录
     */
    @PostMapping("/login")
    public R<User> loginUser(@RequestBody Map map,HttpServletRequest request){

        String phone=(String) map.get("phone");

        String password=(String)map.get("password");
        String code=(String) map.get("code");
        log.info("login,电话号码:"+phone);
        if(!RegxPhoneNumber.regxPhone(phone)){
            return R.error("请输入正确的手机号");
        }
        HttpSession session = request.getSession();
        log.info("login:session"+session.getId());

//        String vertifyCode= (String) session.getAttribute(phone);
//        session.removeAttribute(phone);
        if(true){
            User user=new User();
            user.setPhone(phone);
            user.setPassword(password);
            LambdaUpdateWrapper<User> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(User::getPhone,phone).eq(User::getPassword,password);
            User user_login = userService.getOne(lambdaUpdateWrapper);
            if(user_login!=null){
                user_login.setPassword("");
                return R.success(user_login);
            }

        }else {
            R.error("验证码错误");
        }
        return R.error("登录失败");
    }
    /**
     * 图片验证码
     */
    @GetMapping("/getCode")
    public R<String> getCode( String phone, HttpServletRequest request, HttpServletResponse response){
        if(phone==null){
            return R.error("请输入手机号");
        }
        log.info("电话号码"+phone);
        if(!RegxPhoneNumber.regxPhone(phone)){
            return R.error("请输入正确的手机号");
        }
        HttpSession session = request.getSession();
        log.info("sessionID:"+session.getId());
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 100, 4, 4);
        try {
            captcha.write(response.getOutputStream());

            String code = captcha.getCode();
            session.setAttribute(phone,code);
            log.info("验证码："+code);
            log.info("验证码：session:"+session.getId());
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success("验证码获取成功");
    }

    @PostMapping("/register")
    public R<User> registerUser(@RequestBody Map map,HttpServletRequest request){

        String phone=(String) map.get("phone");
        String password=(String) map.get("password");
        String passwordAgain=(String) map.get("passwordAgain");
        String name=(String) map.get("name");

        int sex= Integer.parseInt( (String) map.get("sex"));
//        String code= (String) map.get("code");
        if(!RegxPhoneNumber.regxPhone(phone)){
            return R.error("请输入正确的手机号");
        }
        if("".equals(passwordAgain)||"".equals(passwordAgain)){
            return R.error("注册失败");
        }
        if(!password.equals(passwordAgain)){
            return R.error("注册失败");
        }
        HttpSession session = request.getSession();
//        String vertifyCode = (String) session.getAttribute(phone);
//        session.removeAttribute(phone);
        if(true){
            User user=new User();
            user.setUserName(name);
            user.setPhone(phone);
            user.setPassword(password);
            user.setSex(sex);
            if(user!=null&&user.getPassword()!=null&&user.getPhone()!=null){
                userService.save(user);
                return R.success(user);
            }
        }
            return R.error("注册失败");
    }

    /**
     * 获取所有
     * @return
     */
//    @GetMapping("/searchAll")
//    public R<List<EmployerCompany>> searchAll(){
//        List<EmployerCompany> employerCompanyList = employerMapper.getEmployerAllList();
//        return R.success(employerCompanyList);
//    }

    /**
     *     根据ID获取user
     */
    @GetMapping("/userInfo")
    public R<User> getUserById(String ID){
        log.info("ID"+ID);
        User user = userService.getById(ID);
        if(user!=null){
            user.setPassword(MD5.create().digestHex(new Date().toString()));
            log.info(user.toString());
        }
        return  R.success(user);
    }

    /**
     * 修改基本信息
     * @param user
     * @return
     */
    @PostMapping("/changeInfo")
    public R<User> updateUser(User user){
        boolean flag = userService.updateById(user);
        if(flag){
            return R.success(user);
        }
        return R.error("修改失败");
    }

    /**
     * 修改密码
     * @return
     */
    @PostMapping("/changePassword")
    public R<String> updatePassword(@RequestBody Map map){
        long userId= Long.parseLong((String) map.get("userId"));
        String oldPassword= (String) map.get("oldPassword");
        LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getId,userId).eq(User::getPassword,oldPassword);
        User userOne = userService.getOne(lambdaQueryWrapper);
        if(userOne!=null){
            String newPassword= (String) map.get("newPassword");
            String newPasswordAgain= (String) map.get("newPasswordAgain");
            if(!(newPassword.trim().equals("")&&newPasswordAgain.trim().equals(""))){
                if(newPassword.equals(newPasswordAgain)){
                    userOne.setPassword(newPassword);
                    boolean flag = userService.updateById(userOne);
                    if(flag){
                        return R.success("修改成功");
                    }
                }
            }
        }
        return R.error("修改失败");

    }

}
